package top.zsyle.sycc.service.impl;

import bo.CourseOrderPayBo;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.params.shadow.com.univocity.parsers.common.processor.core.AbstractInputValueSwitch;
import top.zsyle.sycc.domain.CourseOrder;
import top.zsyle.sycc.domain.PayOrder;
import top.zsyle.sycc.dto.PayOrderApplyDto;
import top.zsyle.sycc.exception.GlobalException;
import top.zsyle.sycc.exception.GlobalExceptionEnum;
import top.zsyle.sycc.mapper.PayOrderMapper;
import top.zsyle.sycc.service.IPayOrderService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.zsyle.sycc.utils.AssertUtil;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhongshiyi
 * @since 2023-01-10
 */
@Service
@Slf4j
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {

    @Override
    public PayOrder selectByOrderNo(String orderNo) {
        Wrapper<PayOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no",orderNo);
        return selectOne(wrapper);
    }

    @Override
    public void insertByInfo(CourseOrderPayBo courseOrderPayBo) {
        PayOrder payOrder = new PayOrder();
        payOrder.setOrderNo(courseOrderPayBo.getOrderNo());
        payOrder.setPayType(courseOrderPayBo.getPayType());
        payOrder.setSubject(courseOrderPayBo.getTitle());
        payOrder.setAmount(courseOrderPayBo.getTotalAmount());
        payOrder.setUserId(courseOrderPayBo.getUserId());
        payOrder.setPayStatus(PayOrder.WAITE_PAY);
        payOrder.setCreateTime(new Date());
        insert(payOrder);
    }

    /**
     * 支付申请连接支付宝进行支付，返回一个form表单，前端得到后打开
     * @param payOrderApplyDto
     * @return
     */
    @Override
    public String payApply(PayOrderApplyDto payOrderApplyDto) {
        Integer payType = payOrderApplyDto.getPayType();
        String callUrl = payOrderApplyDto.getCallUrl();
        //1.参数校验 JSR303校验
        //2.业务校验
        //2.1 查询支付单是否已经生成
        PayOrder payOrder = selectByOrderNo(payOrderApplyDto.getOrderNo());
        AssertUtil.isNotNull(payOrder, GlobalExceptionEnum.ERROR);
        //2.2 查询支付单的支付状态是否为待支付
        AssertUtil.isEquals(CourseOrder.WAITE_PAY.toString(),payOrder.getPayStatus().toString(),GlobalExceptionEnum.ERROR);
        //3.发起支付
        switch (payType){
            case 1:
                return aliPay(payOrder,callUrl);
            case 2:
                //todo 调用微信支付接口
                log.info("调用微信支付接口");
                return "";
            case 3:
                //todo 调用网银支付接口
                log.info("调用网银支付接口");
                return "";
            default:
                throw new GlobalException(GlobalExceptionEnum.ERROR);
        }
    }

    private String aliPay(PayOrder payOrder, String callUrl) {
        try {
            String orderNo = payOrder.getOrderNo();
            // 2. 发起API调用（以创建当面付收款二维码为例）
            //AlipayTradePrecreateResponse response = Payment.FaceToFace().preCreate("Apple iPhone11 128G", "2234567890", "5799.00");
            AlipayTradePagePayResponse response = Factory.Payment.Page().pay(payOrder.getSubject(), orderNo, payOrder.getAmount().toString(), callUrl);
            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                log.info("调用支付宝接口成功！订单号为："+orderNo);
                return response.getBody();
            } else {
                System.err.println("调用支付宝接口失败，原因：" + response.getBody() + "，" + response.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("调用遭遇异常，原因：" + e.getMessage());
            throw new GlobalException(GlobalExceptionEnum.ERROR);
        }
        return null;
    }
}
